<template>
  <!-- 工具栏 -->
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
    <!-- 左侧按钮 -->
    <div>
      <el-button type="primary" @click="openAddDialog">新增</el-button>
      <el-button type="danger" :disabled="!multipleSelection.length" @click="deleteSelected">批量删除</el-button>
    </div>
    <!-- 右侧图标 -->
    <div>
      <el-icon style="margin: 0 8px; cursor: pointer;" @click="onRefresh"><Refresh /></el-icon>
      <el-icon style="margin: 0 8px; cursor: pointer;" @click="onSetting"><Setting /></el-icon>
      <el-icon style="margin: 0 8px; cursor: pointer;" @click="onFilter"><Filter /></el-icon>
    </div>
  </div>
  <!-- 表格 -->
  <el-table
    ref="mainTable"
    v-if="showTable"
    :data="tableData"
    border
    @selection-change="handleSelectionChange"
    style="width: 100%"
    row-key="id"
  >
    <el-table-column type="selection" width="55" />

    <el-table-column label="序号" width="60" >
      <template #header>
        <div style="text-align:center;">序号</div>
        <div style="text-align:center; color:#aaa;"></div>
      </template>
      <template #default="scope">
        {{ (page - 1) * pageSize + scope.$index + 1 }}
      </template>
    </el-table-column>

    <el-table-column prop="storeName" label="商品名称" width="100">
      <template #header>
        <div>商品名称</div>
        <div v-if="showQuery">
          <el-select
            v-model="searchForm.storeName"
            placeholder="输入进行查询"
            filterable
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          >
            <el-option
              v-for="item in storeOptions"
              :key="item.id"
              :label="item.storeName"
              :value="item.storeName"
            />
          </el-select>
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="batch" label="生产批次">
      <template #header>
        <div>生产批次</div>
        <div v-if="showQuery">
          <el-input
            v-model="searchForm.batch"
            placeholder="输入进行查询"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="expiration" label="保质期（天）">
      <template #header>
        <div>保质期（天）</div>
        <div v-if="showQuery">
          <el-input
            v-model="searchForm.expiration"
            placeholder="输入进行查询"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="license" label="生产许可证号">
      <template #header>
        <div>生产许可证号</div>
        <div v-if="showQuery">
          <el-input
            v-model="searchForm.license"
            placeholder="输入进行查询"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="company" label="生产企业">
      <template #header>
        <div>生产企业</div>
        <div v-if="showQuery">
          <el-input
            v-model="searchForm.company"
            placeholder="输入进行查询"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
    </el-table-column>

   <el-table-column prop="completeness" label="信息完整度" width="180">
  <template #default="scope">
    <el-progress
      :percentage="Number(scope.row.completeness)"
      :color="scope.row.completeness == 100 ? '#67C23A' : '#F56C6C'"
      :format="formatPercent"
      stroke-width="18"
      style="width: 120px"
    />
  </template>
</el-table-column>

    <el-table-column prop="creator" label="创建人">
      <template #header>
        <div>创建人</div>
        <div v-if="showQuery">
          <el-input
            v-model="searchForm.creator"
            placeholder="输入进行查询"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="creatorDate" label="创建时间" width="180">
      <template #header>
        <div>创建时间</div>
        <div v-if="showQuery">
          <el-date-picker
            v-model="searchForm.creatorDate"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
      <template #default="scope">
        {{ formatDate(scope.row.creatorDate) }}
      </template>
    </el-table-column>

    <el-table-column prop="updator" label="修改人">
      <template #header>
        <div>修改人</div>
        <div v-if="showQuery">
          <el-input
            v-model="searchForm.updator"
            placeholder="输入进行查询"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="updatorDate" label="修改时间" width="180">
      <template #header>
        <div>修改时间</div>
        <div v-if="showQuery">
          <el-date-picker
            v-model="searchForm.updatorDate"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间"
            clearable
            size="small"
            style="width: 100%; margin-top: 2px"
            @change="onSearch"
          />
        </div>
      </template>
      <template #default="scope">
        {{ formatDate(scope.row.updatorDate) }}
      </template>
    </el-table-column>

    <el-table-column label="操作" width="250">
      <template #header>
        <div>操作</div>
      
      </template>
      <template #default="scope">
        <el-link type="primary" @click="showDetail(scope.row)">详情</el-link>&emsp13;
        <el-link type="primary" @click="openEditDialog(scope.row)">修改</el-link>&emsp13;
        <el-link type="primary" @click="">导出溯源码</el-link>&emsp13;
        <el-link type="danger" @click="deleteRow(scope.row)">删除</el-link>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    v-model:current-page="page"
    v-model:page-size="pageSize"
    :total="total"
    @current-change="fetchData"
    @size-change="fetchData"
    layout="total, sizes, prev, pager, next, jumper"
    :page-sizes="[15, 30, 50, 100]"
  />

  <!-- 新增/编辑弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form :model="form" label-width="110px" :rules="rules">
      <el-form-item label="商品名称" prop="sid" required>
        <el-select
          v-model="form.sid"
          filterable
          placeholder="请选择商品名称"
          style="width: 100%"
        >
          <el-option
            v-for="item in storeOptions"
            :key="item.id"
            :label="item.storeName"
            :value="item.id"
           
          >
            {{ item.storeName }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次" prop="batch" required>
        <el-input
          v-model="form.batch"
          maxlength="30"
          show-word-limit
          placeholder="请输入生产批次（最多30位）"
        />
      </el-form-item>
      <el-form-item label="保质期（天）" prop="expiration" required>
        <el-input
          v-model="form.expiration"
          maxlength="5"
          show-word-limit
          placeholder="请输入保质期（最多5位数字）"
          @input="onExpirationInput"
        />
      </el-form-item>
      <el-form-item label="生产许可证号" prop="license" required>
        <el-input
          v-model="form.license"
          maxlength="30"
          show-word-limit
          placeholder="请输入生产许可证号（最多30位数字或字母）"
          oninput="this.value=this.value.replace(/[^a-zA-Z0-9]/g,'').slice(0,30)"
        />
      </el-form-item>
      <el-form-item label="生产企业" prop="company" required>
        <el-input
          v-model="form.company"
          maxlength="30"
          show-word-limit
          placeholder="请输入生产企业（最多30位，不能含特殊字符）"
          @input="onCompanyInput"
        />
      </el-form-item>
      <el-form-item label="封面图" prop="picture">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:5295/api/Imgs/Imgs"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
        >
          <div v-if="form.picture" style="position: relative; display: inline-block;">
            <img :src="form.picture" class="avatar" />
            <!-- 删除按钮 -->
            <el-icon
              style="position: absolute; top: 2px; right: 2px; cursor: pointer; background: rgba(255,255,255,0.7); border-radius: 50%;"
              @click.stop="removePicture"
            >
              <Close />
            </el-icon>
          </div>
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed,watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http  from '@/http/axioshttp'
import { Plus, Refresh, Setting, Filter, Close } from '@element-plus/icons-vue'
import { useCounterStore } from '@/stores/counter'
import { useRouter } from 'vue-router'
const router = useRouter()
const pinia=useCounterStore()
import { useRoute } from 'vue-router'

const route = useRoute()
function formatPercent(percent: number) {
  return percent === 100 ? '100%' : parseInt(percent as any) + '%'
}
//商品名称（下拉框）
interface StoreItem {
  id: number
  storeName: string
}
const storeOptions = ref<StoreItem[]>([])

const fetchStoreOptions = async () => {
  const res = await http.get('/api/Basic/GetStore')
  storeOptions.value = (res.data.data || []).filter((item: any) => item && item.id && item.storeName)
}

const showTable = ref(true)
const tableData = ref<any[]>([])
// 查询 显示
const searchForm = reactive({
  storeName: '',
  batch: '',
  expiration: '',
  license: '',
  company: '',
  completeness: '',
  creator: '',
  creatorDate: '',
  updator: '',
  updatorDate: ''
})
const total = ref(0)
const page = ref(1)
const pageSize = ref(15) 
const multipleSelection = ref<any[]>([])
const onSearch = () => {
  page.value = 1
  fetchData()
}

const fetchData = async () => {
  const res = await http.get('/api/Basic/GetBasic', {
    params: {
      PageIndex: page.value,
      PageSize: pageSize.value,
      StoreName: searchForm.storeName,
      Batch: searchForm.batch,
      Expiration: searchForm.expiration,
      License: searchForm.license,
      Company: searchForm.company,
      Creator: searchForm.creator,
      CreatorDate: searchForm.creatorDate,
      Updator: searchForm.updator,
      UpdatorDate: searchForm.updatorDate
    }
  })
  tableData.value = res.data.data || []
  total.value = res.data.totalCount || 0
}
onMounted(() => {
  fetchStoreOptions()
  fetchData()
})

//添加修改删除
interface BasicItem {
  id?: number
  sid: number | null // 商品ID
  batch: string
  expiration: number | null
  license: string
  company: string
  picture?: string,
  creator:string 
  creatorDate?: string | Date
  updator?: string
  updatorDate?: string | Date
}

const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const form = ref<Partial<BasicItem>>({
  id: undefined,
  sid: null,
  batch: '',
  expiration: null,
  license: '',
  company: '',
  picture: '',
  creator: pinia.account.UserName,
  updator: pinia.account.UserName
})

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const openAddDialog = () => {

  dialogTitle.value = '新增'
   form.value = {
    id: undefined,
    sid: null,
    batch: '',
    expiration: null,
    license: '',
    company: '',
    picture: '',
    creator: pinia.account.UserName,
    updator: pinia.account.UserName
  }
  dialogVisible.value = true
}

const openEditDialog = (row: BasicItem) => {
  dialogTitle.value = '修改'
  form.value = { ...row } 
  dialogVisible.value = true
}

const submitForm = async () => {
  const payload = {
    Id: form.value.id, 
    Sid: form.value.sid,
    Batch: form.value.batch,
    Expiration: form.value.expiration,
    License: form.value.license,
    Company: form.value.company,
    Picture: form.value.picture,
    Creator: pinia.account.UserName, // 新增时
    Updator: pinia.account.UserName  // 修改时
  }
  let res;
  if (form.value.id) {
    res = await http.put('/api/Basic/UpdateBasic', payload)
  } else {
    res = await http.post('/api/Basic/AddBasic', payload)
  }
  if (res.data.code === 200) {
    ElMessage.success(res.data.msg || '操作成功')
    dialogVisible.value = false
    fetchData()
  }
  else if(res.data.code === 500){
    ElMessage.success(res.data.msg || '操作成功')
  } 
  else {
    ElMessage.error(res.data.msg || '操作失败')
  }
}
//验证规则
const rules = {
  sid: [
    { required: true, message: '商品名称不能为空', trigger: 'change' }
  ],
  batch: [
    { required: true, message: '生产批次不能为空', trigger: 'blur' },
    { max: 30, message: '生产批次最多30位字符', trigger: 'blur' }
  ],
  expiration: [
    { required: true, message: '保质期不能为空', trigger: 'blur' },
    { pattern: /^[0-9]{1,5}$/, message: '请输入最多5位数字', trigger: 'blur' }
  ],
  license: [
    { required: true, message: '生产许可证号不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{1,30}$/, message: '只能输入数字和字母，最多30位', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '生产企业不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,30}$/, message: '只能输入中文、字母、数字，最多30位', trigger: 'blur' }
  ]
}
function onExpirationInput(e: Event) {
  // 只保留数字，最多5位
  const val = String(form.value.expiration ?? '').replace(/[^0-9]/g, '').slice(0, 5)
  // 只在有值时转为数字，否则设为 null
  form.value.expiration = val ? Number(val) : null
}

function onCompanyInput() {
  // 只允许输入中文、字母、数字，自动截断为30位
  form.value.company = (form.value.company || '').replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '').slice(0, 30)
}
//单个删除
function deleteRow(row: BasicItem) {
  ElMessageBox.confirm(
    '确认删除该溯源商品？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
      closeOnPressEscape: false,
    }
  ).then(async () => {
    const res = await http.put('/api/Basic/DelBasic', { id: row.id })
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error('删除失败，请稍后再试')
    }
  }).catch(() => {
    ElMessage.warning('已取消当前操作');
  })
}
//批量删除
const deleteSelected = () => {
  const count = multipleSelection.value.length
  if (!count) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(
    `确认删除已选的 ${count} 个溯源商品？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
      closeOnPressEscape: false,
    }
  ).then(async () => {
    const ids = multipleSelection.value.map(item => item.id)
    const res = await http.put('/api/Basic/DelMultiple', { ids })
    if (res.data.code === 200) {
      ElMessage.success(`已删除 ${count} 个溯源商品`)
      fetchData()
    } else {
      ElMessage.error('删除失败，请稍后再试')
    }
  }).catch(() => {
   fetchData();
  })
}
//上传图片
const handleUploadSuccess = (res: any) => {
  form.value.picture = typeof res === 'string' ? res : res.url
}
const beforeUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) ElMessage.error('只能上传 JPG/PNG 格式图片!')
  if (!isLt2M) ElMessage.error('图片大小不能超过 2MB!')
  return isJPG && isLt2M
}

function removePicture() {
  form.value.picture = ''
}



function formatDate(date: string | Date | undefined) {
  if (!date) return ''
  const d = new Date(date)
  const pad = (n: number) => n.toString().padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

//三个图标
const onRefresh = () => {
  fetchData()
}
const onSetting = () => {
  showTable.value = !showTable.value
}
const showQuery = ref(true)
const onFilter = () => {
  showQuery.value = !showQuery.value
}
//跳转页面
function showDetail(row:any) {
  router.push({ path: '/getdetail', query: {  batch: row.batch } })
}






</script>

<style scoped>
.el-table th {
  background: #fafafa;
}
.el-table .el-input,
.el-table .el-select,
.el-table .el-date-picker {
  width: 100%;
}
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 6px;
  object-fit: cover;
}
.avatar-uploader-icon {
  font-size: 48px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}
.el-table__append-wrapper {
  padding: 0 !important;
}
.el-table__append-wrapper tr td {
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
  padding: 0;
  height: 40px; /* 可根据实际表格行高调整 */
}
.table-query-row {
  margin-bottom: -1px;
}
.table-query-row .el-input,
.table-query-row .el-select,
.table-query-row .el-date-picker {
  width: 100%;
}
.table-query-row td {
  padding: 0 8px;
  height: 40px;
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
}
.report-img {
  border: 1px solid red;
}
</style>
